const db = require('../../database/index')
const bcrypt = require('bcryptjs')

// 获取用户信息
const handlerUserinfo = (req, res) => {
  const sql = 'select id,username,nickname,email,user_pic from ev_users where id=?'
  db.query(sql, [req.user.id], (err, results) => {
    if (err) {
      return res.cc(err.message)
    } else if (results.length > 0) {
      res.send({
        status: 1,
        msg: '获取成功',
        data: results[0]
      })
    } else {
      return res.cc('出现异常')
    }
  })
}

// 更新用户信息
const handlerUpdateUserinfo = (req, res) => {
  const userInfo = req.body
  const sql = 'update ev_users set ? where id=?'
  db.query(sql, [userInfo, req.user.id], (err, results) => {
    if (err) {
      return res.cc(err.message)
    } else if (results.affectedRows > 0) {
      return res.cc('更新成功')
    } else {
      return res.cc('程序异常')
    }
  })
}

// 修改密码
const handlerModifyPassword = (req, res) => {
  const psw = req.body.newPsw
  const oldPassword = req.body.oldPsw
  // 加密密码
  const bcryptPsw = bcrypt.hashSync(psw, 10)

  const sql = 'select password from ev_users where id=?'
  // 检查旧密码是否正确
  db.query(sql, [req.user.id], (err, results) => {
    if (err) {
      return res.cc(err.message)
    } else if (results.length > 0) {
      // 比较新旧密码
      if (bcrypt.compareSync(oldPassword, results[0].password)) {
        modifyPassword()
      } else {
        return res.cc('旧密码不正确')
      }
    }
  })
  // 如果密码正确
  const modifyPassword = () => {
    const sqlStr = 'update ev_users set password=? where id=?'
    db.query(sqlStr, [bcryptPsw, req.user.id], (err, results) => {
      if (err) {
        return res.cc(err.message)
      } else if (results.affectedRows > 0) {
        return res.cc('修改成功')
      }
    })
  }
}

const handlerUpdateAvatar = (req, res) => {
  const sql = 'update ev_users set user_pic=? where id=?'
  db.query(sql, [req.body.user_pic, req.user.id], (err, results) => {
    if (err) {
      return res.cc(err.message)
    } else if (results.affectedRows > 0) {
      return res.cc('更新头像成功',1)
    } else {
      return res.cc('未知错误')
    }
  })
}

module.exports = {
  handlerUserinfo,
  handlerUpdateUserinfo,
  handlerModifyPassword,
  handlerUpdateAvatar
}
